//
//  FriendInfoListVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/20.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "FriendInfoListVC.h"
#import "UserHeaderView.h"
#import "YBContentModel.h"
#import "EVCPopInputView.h"
#import "ZXConfirmButton.h"
#import <LKDBHelper/LKDBHelper.h>
#import "YBApiManager+Friend.h"
#import "ChatContentVC.h"
#import "YBApiManager+Friend.h"
#import "Friend_groupListVC.h"
#import "CRPreview.h"

@interface FriendInfoListVC ()

@property (nonatomic, strong) UserHeaderView *userView;
@property (nonatomic, strong) ZXConfirmButton *sendMsgBtn;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIBarButtonItem *rightBarBtnItem;

@end

@implementation FriendInfoListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupDatasource];
    [self updateUI];
    if (self.listType > 1) {
        [self requestUserDatas];
    }
    self.title = @"详情";
}
- (void)requestUserDatas {
    @weakify(self);
    [MBProgressHUD showActivityMessageInView:@""];
    [[YBApiManager.shareManager searchUserWithUid:self.user.friend_id?:self.user.ID] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        NSDictionary *dataDic = [x objectForKey:@"data"];
        NSString *avatar = self.user.avatar;
        NSString *name = self.user.username;
        [self.user mj_setKeyValues:dataDic];
        if ([avatar isEqualToString:self.user.avatar] == NO ||
            (self.user.nickname.isHaveStr == NO && [name isEqualToString:self.user.username] == NO)) {
            [[NSNotificationCenter defaultCenter] postNotificationName:notification_Friend_Info_Changed object:self.user];
        }
        
        @strongify(self);
        [self setupDatasource];
        [self updateUI];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (void)setupUI {
    
    self.userView = [[UserHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 200)];
    self.tableView.tableHeaderView = self.userView;
    self.userView.rightArrowImgView.hidden = YES;
    [self.userView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(ScreenWidth);
    }];
    [self.tableView layoutIfNeeded];
    self.tableView.tableHeaderView = self.userView;
    @weakify(self);
    [[self.userView.editIconBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        CRPreview *preview = [[CRPreview alloc] initWithImage:self.userView.iconImgView.image];
        [preview show];
    }];
    
    [self.tableView customRegisterClassWithName:@"MineCell"];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 300, ScreenWidth, 65+20)];
    bottomView.backgroundColor = UIColor.clearColor;
    self.sendMsgBtn = [ZXConfirmButton confirmButton];
    self.sendMsgBtn.k_title(@"发送消息");
    self.sendMsgBtn.frame = CGRectMake(50, 30, ScreenWidth-100, 40);
    [self.sendMsgBtn addTarget:self action:@selector(didClickBottomBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.sendMsgBtn];
    self.tableView.tableFooterView = bottomView;
    self.bottomView = bottomView;
}
- (void)setupDatasource {
    
    NSArray *dataArr = @[@{@"title": @"设置备注",
                           @"rightText": self.user.nickname?:@"",
                           @"icon": @"arrow_right",
                           @"vc": @""
                           },
                         @{@"title": @"性别",
                           @"rightText": self.user.gender?:@"",
                           @"icon": @"",
                           @"vc": @""
                           },
                         @{@"title": @"生日",
                           @"rightText": self.user.birthday?:@"",
                           @"icon": @"",
                           @"vc": @""
                           },
                         @{@"title": @"地区",
                           @"rightText": self.user.region?:@"",
                           @"icon": @"mine_addr",
                           @"vc": @""
                           },
                         @{@"title": @"个人签名",
                           @"rightText": self.user.bio?:@"",
                           @"icon": @"",
                           @"vc": @""
                           }];
    
    self.dataSource = [YBContentModel mj_objectArrayWithKeyValuesArray:dataArr];
    for (YBContentModel *obj in self.dataSource) {
        obj.cellId = @"MineCell";
    }
    
    if (self.user.isFriend == YES && self.user.is_black == NO) {
        YBContentModel *model = [YBContentModel mj_objectWithKeyValues:@{@"title": @"分组",
                                                                         @"rightText": self.user.sort_name?:@"",
                                                                         @"icon": @"arrow_right",
                                                                         @"vc": @""
                                                                         }];
        model.cellId = @"MineCell";
        [self.dataSource addObject:model];
    }
    
    [self.tableView reloadData];
}

- (void)updateUI {
    [self.userView.iconImgView sd_setImageWithURL:self.user.avatar.toURL placeholderImage:UIImage.k_imgName(@"placeholder_user")];
    self.userView.nicknameLabel.text = self.user.username;
    self.userView.mobileLabel.text = [NSString stringWithFormat:@"ID: %@",self.user.friend_id?:self.user.ID];
    
    self.navigationItem.rightBarButtonItem = nil;
    if (self.user.isFriend == YES) {
        self.sendMsgBtn.k_title(@"发送消息");
        if ([self.user.friend_id isEqualToString:kUsermanager.me.ID] == NO) {
            self.navigationItem.rightBarButtonItem = self.rightBarBtnItem;
        }
    } else if (self.listType == 1){
        self.sendMsgBtn.k_title(@"同意好友请求");
    } else {
        self.sendMsgBtn.k_title(@"添加到通讯录");
    }
    self.userView.msgContent = self.user.content;
    [self.tableView layoutIfNeeded];
    self.tableView.tableHeaderView = self.userView;
}
- (UIBarButtonItem *)rightBarBtnItem {
    if (_rightBarBtnItem == nil) {
        UIButton *btn = UIButton.k_init().k_img(UIImage.k_imgName(@"global_more"));
        btn.tintColor = UIColor.whiteColor;
        
        _rightBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        @weakify(self);
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            NSArray *titles = nil;
            if (self.user.is_black == YES) {
                titles = @[@"删除好友", @"移出黑名单"];
            } else {
                titles = @[@"删除好友", @"移入黑名单"];
            }
            [LBXAlertAction showActionSheetWithTitle:@"更多" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitle:titles chooseBlock:^(NSInteger buttonIdx) {
                if (buttonIdx == 1) {
                    [self didClickDeleteFriendBtnAction];
                } else if (buttonIdx == 2) {
                    [self didClickMoveBlacklistBtnAction];
                }
            }];
        }];
    }
    return _rightBarBtnItem;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 65;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    return self.bottomView;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YBContentModel *model = [self.dataSource objectAtIndex:indexPath.row];
    
    if ([model.title isEqualToString:@"设置备注"] == YES) {
        EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"设置备注" subTitle:nil placehold:@"请输入备注" preset:model.rightText];
        popView.limitTextNum = 15;
        popView.nulTextCanSend = YES;
        [popView show];
        [popView clickButtonAction:^(NSInteger index, NSString *content) {
            if (index == 1) {
                [self changeNicknameActionWithModel:model newValue:content];
            }
        }];
    } else if ([model.title isEqualToString:@"分组"] == YES) {
        
        Friend_groupListVC *groupListVC = [Friend_groupListVC new];
        groupListVC.friendItem = self.user;
        [groupListVC setGroupChanged:^(Address_groupItem * _Nonnull newGroup) {
            self.user.sort_id = newGroup.sort_id;
            self.user.sort_name = newGroup.name;
            [self setupDatasource];
        }];
        [self.navigationController pushViewController:groupListVC animated:YES];
    }
}
- (void)changeNicknameActionWithModel:(YBContentModel *)model newValue:(NSString *)newValue {
    
    if (self.user.isFriend == NO) {
        model.rightText = newValue;
        self.user.nickname = newValue;
        [self.tableView reloadData];
    } else {
        @weakify(self);
        [MBProgressHUD showActivityMessageInView:@""];
        [[YBApiManager.shareManager setFriendRemarkWithId:self.user.friend_id?:self.user.ID nickname:newValue] subscribeNext:^(id  _Nullable x) {
            @strongify(self);
            [MBProgressHUD hideHUD];
            model.rightText = newValue;
            self.user.nickname = newValue;
            [self.tableView reloadData];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:notification_Friend_Info_Changed object:self.user];
            
        } error:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
            if ([error isServerError]) {
                [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
            } else {
                [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
            }
        }];
    }
}

#pragma mark - action
- (void)didClickDeleteBtnAction:(UIButton *)sender {
    
    [MBProgressHUD showActivityMessageInView:@""];
    [[YBApiManager.shareManager deleteFriendWithId:self.user.friend_id] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInView:@"删除成功" timer:1.0f];
        [MsgItem deleteWithWhere:@{@"group_id": self.user.group_id?:@""}];
        [SessionItem deleteWithWhere:@{@"group_id": self.user.group_id?:@""}];
        [kUsermanager updateFriendList];
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_DeleteFriend object:self.user];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
    
}
- (void)didClickBottomBtnAction:(UIButton *)sender {
    if (self.user.isFriend == YES) {
        [self joinChatVC];
    } else if (self.listType == 1){
        [self agreeFriendAction];
    } else {
        [self sendAddFriendAction];
    }
}
- (void)joinChatVC {
    ChatContentVC *chatVc = [ChatContentVC new];
    chatVc.friendItem = self.user;
    [self.navigationController pushViewController:chatVc animated:YES];
}
- (void)sendAddFriendAction {
    
    if (self.user.add_type == 1) {
        [self addFriendActionWithContent:nil];
        return;
    } else if (self.user.add_type == 3) {
        [LBXAlertAction showAlertWithTitle:@"提示" msg:@"对方不允许添加好友！" buttonsStatement:@[@"知道了"] chooseBlock:nil];
        return;
    }
    EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"对方设置了好友验证" subTitle:@"你需要发送验证申请，对方通过后你才能添加为好友" placehold:@"请输入验证内容" preset:nil];
    //    popView.limitTextNum = 15;
    [popView show];
    [popView clickButtonAction:^(NSInteger index, NSString *content) {
        if (index == 1) {
            [self addFriendActionWithContent:content];
        }
    }];
    
}
- (void)addFriendActionWithContent:(NSString *)content {
    [MBProgressHUD showActivityMessageInView:@""];
    
    [[YBApiManager.shareManager addFriendWithId:self.user.ID nickname:self.user.nickname type:self.from content:content] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInView:@"发送请求成功" timer:1.0f];
        
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}
- (void)agreeFriendAction {
    
    [MBProgressHUD showActivityMessageInView:@""];
    @weakify(self);
    [[YBApiManager.shareManager agreeFriendRequestWithFriend_id:self.user.friend_id nickname:self.user.nickname type:self.from] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        
        [MBProgressHUD showTipMessageInWindow:@"已同意好友申请" timer:1.0f];
        @strongify(self);
        
        [kUsermanager updateFriendList];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.agreenApplyBlock) {
                self.agreenApplyBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        });
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (void)didClickDeleteFriendBtnAction {
    [LBXAlertAction showAlertWithTitle:@"提示" msg:@"删除好友后聊天记录也会删除，确认删除？" buttonsStatement:@[@"取消", @"确认"] chooseBlock:^(NSInteger buttonIdx) {
        if (buttonIdx == 1) {
            [self didClickDeleteBtnAction:nil];
        }
    }];
}
- (void)didClickMoveBlacklistBtnAction {
    
    if (self.user.is_black == NO) {
        [MBProgressHUD showActivityMessageInView:@""];
        @weakify(self);
        [[YBApiManager.shareManager moveFriendToBlacklistWithFriend_id:self.user.friend_id] subscribeNext:^(id  _Nullable x) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showTipMessageInView:@"操作成功" timer:1.0f];
            @strongify(self);
            [kUsermanager updateFriend_groupList];
            self.user.is_black = YES;
            [self setupDatasource];
        } error:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
            if ([error isServerError]) {
                [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
            } else {
                [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
            }
        }];
    } else {
        Friend_groupListVC *groupListVC = [Friend_groupListVC new];
        groupListVC.friendItem = self.user;
        [groupListVC setGroupChanged:^(Address_groupItem * _Nonnull newGroup) {
            self.user.sort_id = newGroup.sort_id;
            self.user.sort_name = newGroup.name;
            self.user.is_black = NO;
            [self setupDatasource];
        }];
        [self.navigationController pushViewController:groupListVC animated:YES];
    }
}

@end
